<template>
  <div class="match-center-container">
    <!-- 顶部操作栏 -->
    <div class="page-header">
      <h2 class="page-title">三单匹配管理中心</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="handleGlobalMatch">
          <el-icon>
            <Connection/>
          </el-icon>
          全局匹配
        </el-button>
        <el-button type="primary" @click="handleManualMatch">
          <el-icon>
            <Plus/>
          </el-icon>
          手动匹配
        </el-button>
        <el-button type="primary" @click="exportMatchData">
          <el-icon>
            <Download/>
          </el-icon>
          导出数据
        </el-button>
        <el-button :disabled="selectedItems.length === 0" type="danger" @click="handleBatchDelete">
          <el-icon>
            <Delete/>
          </el-icon>
          批量删除
        </el-button>
        <el-button type="primary" @click="refreshData">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline label-width="100px" @keyup.enter="handleSearch">
        <el-form-item label="匹配状态">
          <el-select v-model="searchForm.matchStatus" clearable placeholder="请选择匹配状态" style="width: 180px">
            <el-option label="全部" value=""></el-option>
            <el-option label="匹配成功" value="匹配成功"></el-option>
            <el-option label="部分匹配" value="部分匹配"></el-option>
            <el-option label="待匹配" value="待匹配"></el-option>
            <el-option label="匹配异常" value="匹配异常"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单据编号">
          <el-input v-model="searchForm.documentNumber" clearable placeholder="订单号/发票号/收货单号"></el-input>
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="searchForm.supplierName" clearable placeholder="供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="匹配日期">
          <el-date-picker
              v-model="searchForm.dateRange"
              :shortcuts="dateShortcuts"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon>
              <Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 主要内容区域 -->
    <el-card class="content-card">
      <el-tabs v-model="activeMainTab" @tab-click="handleMainTabClick">
        <el-tab-pane label="匹配概览" name="overview">
          <match-statistics-panel/>
        </el-tab-pane>
        <el-tab-pane label="匹配记录" name="records">
          <!-- 匹配记录子标签页 -->
          <el-tabs v-model="activeRecordsTab" @tab-click="handleRecordsTabClick">
            <el-tab-pane label="全部" name="all"></el-tab-pane>
            <el-tab-pane label="待匹配" name="pending">
              <template #label>
                <span>待匹配</span>
                <el-badge v-if="counters.pending > 0" :value="counters.pending" class="item"/>
              </template>
            </el-tab-pane>
            <el-tab-pane label="匹配成功" name="success">
              <template #label>
                <span>匹配成功</span>
                <el-badge v-if="counters.success > 0" :value="counters.success" class="item"/>
              </template>
            </el-tab-pane>
            <el-tab-pane label="部分匹配" name="partial">
              <template #label>
                <span>部分匹配</span>
                <el-badge v-if="counters.partial > 0" :value="counters.partial" class="item"/>
              </template>
            </el-tab-pane>
            <el-tab-pane label="匹配异常" name="exception">
              <template #label>
                <span>匹配异常</span>
                <el-badge v-if="counters.exception > 0" :value="counters.exception" class="item"/>
              </template>
            </el-tab-pane>
          </el-tabs>

          <!-- 匹配记录表格 -->
          <match-records-table
              ref="recordsTableRef"
              :active-tab="activeRecordsTab"
              :search-params="searchParams"
              @view-detail="viewDetail"
              @manual-match="manualMatch"
              @selection-change="handleSelectionChange"
          />
        </el-tab-pane>
        <el-tab-pane label="可匹配订单" name="available">
          <!-- 可匹配订单表格 -->
          <match-available-orders-table
              ref="availableOrdersTableRef"
              :search-params="searchParams"
              @match="handleOrderMatch"
              @view="viewOrderDetail"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 匹配详情对话框 -->
    <match-detail-dialog
        v-model:visible="detailDialogVisible"
        :match-id="currentMatchId"
        @close="handleDetailDialogClose"
    />

    <!-- 匹配操作对话框 -->
    <match-operation-dialog
        v-model:visible="matchDialogVisible"
        :pre-selected-order-id="selectedOrderId"
        @success="handleMatchSuccess"
    />

    <!-- 全局匹配结果对话框 -->
    <el-dialog v-model="globalMatchDialogVisible" title="全局匹配结果" width="800px">
      <div v-if="globalMatchResults.length === 0" class="no-data">
        <el-empty description="没有找到可匹配的数据"></el-empty>
      </div>
      <div v-else>
        <el-table :data="globalMatchResults" border style="width: 100%">
          <el-table-column label="序号" type="index" width="60"></el-table-column>
          <el-table-column label="匹配结果" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.success ? 'success' : 'danger'">
                {{ scope.row.success ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" min-width="120" prop="orderNumber"></el-table-column>
          <el-table-column label="收货单编号" min-width="120" prop="receiptNumber"></el-table-column>
          <el-table-column label="发票编号" min-width="120" prop="invoiceNumber"></el-table-column>
          <el-table-column label="供应商" min-width="150" prop="supplierName"></el-table-column>
          <el-table-column label="匹配ID" min-width="180" prop="matchId"></el-table-column>
          <el-table-column label="消息" min-width="200" prop="message"></el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="globalMatchDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="refreshData">刷新数据</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {computed, nextTick, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useRouter} from 'vue-router';
import {Connection, Delete, Download, Plus, Refresh, Search} from '@element-plus/icons-vue';
import {MatchQueryParams, MatchService} from '@/api/match-service';

// 导入组件
import MatchStatisticsPanel from '@/components/match/MatchStatisticsPanel.vue';
import MatchRecordsTable from '@/components/match/MatchRecordsTable.vue';
import MatchAvailableOrdersTable from '@/components/match/MatchAvailableOrdersTable.vue';
import MatchDetailDialog from '@/components/match/MatchDetailDialog.vue';
import MatchOperationDialog from '@/components/match/MatchOperationDialog.vue';

const router = useRouter();

// 标签页状态
const activeMainTab = ref('overview');
const activeRecordsTab = ref('all');

// 表格引用
const recordsTableRef = ref<InstanceType<typeof MatchRecordsTable> | null>(null);
const availableOrdersTableRef = ref<InstanceType<typeof MatchAvailableOrdersTable> | null>(null);

// 对话框状态
const detailDialogVisible = ref(false);
const matchDialogVisible = ref(false);
const globalMatchDialogVisible = ref(false);
const currentMatchId = ref('');
const selectedOrderId = ref('');
const globalMatchResults = ref<any[]>([]);

// 选中的行
const selectedItems = ref<any[]>([]);

// 数据统计
const counters = reactive({
  pending: 0,
  success: 0,
  partial: 0,
  exception: 0
});

// 搜索表单
const searchForm = reactive({
  matchStatus: '',
  documentNumber: '',
  supplierName: '',
  dateRange: [] as string[]
});

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];

// 计算处理后的搜索参数
const searchParams = computed(() => {
  const params: MatchQueryParams = {};

  if (searchForm.matchStatus) {
    params.matchStatus = searchForm.matchStatus;
  }

  if (searchForm.documentNumber) {
    params.documentNumber = searchForm.documentNumber;
  }

  if (searchForm.supplierName) {
    params.supplierName = searchForm.supplierName;
  }

  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    params.startDate = searchForm.dateRange[0];
    params.endDate = searchForm.dateRange[1];
  }

  return params;
});

// 初始化
onMounted(() => {
  loadCounters();

  // 根据当前标签页加载数据
  nextTick(() => {
    refreshData();
  });
});

// 加载计数器数据
const loadCounters = async () => {
  try {
    const res = await MatchService.getMatchStatistics();
    if (res.code === 200) {
      counters.pending = res.data.pendingCount || 0;
      counters.success = res.data.successCount || 0;
      counters.partial = res.data.partialCount || 0;
      counters.exception = res.data.exceptionCount || 0;
    }
  } catch (error) {
    console.error('加载匹配统计数据失败', error);
  }
};

// 主标签页切换
const handleMainTabClick = () => {
  refreshData();
};

// 记录标签页切换
const handleRecordsTabClick = () => {
  if (recordsTableRef.value) {
    recordsTableRef.value.getMatchList();
  }
};

// 查询
const handleSearch = () => {
  refreshData();
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.matchStatus = '';
  searchForm.documentNumber = '';
  searchForm.supplierName = '';
  searchForm.dateRange = [];

  refreshData();
};

// 刷新数据
const refreshData = () => {
  loadCounters();

  // 根据当前标签页刷新数据
  if (activeMainTab.value === 'records') {
    if (recordsTableRef.value) {
      recordsTableRef.value.getMatchList();
    }
  } else if (activeMainTab.value === 'available') {
    if (availableOrdersTableRef.value) {
      availableOrdersTableRef.value.getAvailableOrders();
    }
  }
};

// 全局匹配
const handleGlobalMatch = async () => {
  try {
    ElMessageBox.confirm('确定要执行全局匹配吗？这可能需要一些时间。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        const res = await MatchService.globalMatch();
        if (res.code === 200) {
          globalMatchResults.value = res.data || [];
          globalMatchDialogVisible.value = true;
          refreshData();
        } else {
          ElMessage.error(res.message || '全局匹配失败');
        }
      } catch (error) {
        console.error('全局匹配失败', error);
        ElMessage.error('全局匹配失败');
      }
    });
  } catch (error) {
    // 用户取消操作
  }
};

// 手动匹配
const handleManualMatch = () => {
  selectedOrderId.value = '';
  matchDialogVisible.value = true;
};

// 查看详情
const viewDetail = (row: any) => {
  currentMatchId.value = row.id || '';
  detailDialogVisible.value = true;
};

// 手动匹配指定记录
const manualMatch = (row: any) => {
  selectedOrderId.value = row.orderId || '';
  matchDialogVisible.value = true;
};

// 查看订单详情
const viewOrderDetail = (row: any) => {
  router.push(`/dashboard/order-detail/${row.id}`);
};

// 匹配指定订单
const handleOrderMatch = (row: any) => {
  selectedOrderId.value = row.id || '';
  matchDialogVisible.value = true;
};

// 选择行
const handleSelectionChange = (selection: any[]) => {
  selectedItems.value = selection;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedItems.value.map(item => item.id);
      const res = await MatchService.batchDeleteMatch(ids);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        refreshData();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('批量删除失败', error);
      ElMessage.error('批量删除失败');
    }
  }).catch(() => {
  });
};

// 导出数据
const exportMatchData = async () => {
  try {
    // 构建查询参数
    const params: MatchQueryParams = {...searchParams.value};

    // 使用 responseType: 'blob' 获取二进制数据
    const res = await MatchService.exportMatch(params);

    // 直接使用响应数据作为Blob
    if (res instanceof Blob) {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(res);
      link.download = `匹配数据_${new Date().getTime()}.xlsx`;
      link.click();
      URL.revokeObjectURL(link.href);

      ElMessage.success('导出成功');
    } else {
      ElMessage.error('导出失败，返回数据格式不正确');
    }
  } catch (error) {
    console.error('导出数据失败', error);
    ElMessage.error('导出数据失败');
  }
};

// 详情对话框关闭
const handleDetailDialogClose = () => {
  currentMatchId.value = '';
};

// 匹配成功
const handleMatchSuccess = () => {
  refreshData();
};
</script>

<style scoped>
.match-center-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.content-card {
  min-height: 500px;
}

.no-data {
  padding: 40px 0;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 